﻿using Core.Business.ProjectModule;
using Core.Business.SocketModel;
using Core.Business.UserModule;
using Core.DataAccess.Model.Project.Queue;
using Core.DataAccess.Model.Projects;
using Core.Framework.Model.Common;
using Core.Framework.Redis;
using Core.IBusiness.IProjectModule;
using Core.IBusiness.ISocketModel;
using Core.IBusiness.IUserModule;
using Core.Middleware.WebSockets;
using log4net.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using LogDashboard;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore.Entities;

namespace Core.WebSocketApi
{
    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            CoreStartupHelper.Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddLogDashboard();

            services
                 .AddMvc()
                 .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            BuildServiceProvider
                .ServiceCollection

                .AddScoped<ProjectContext>()
                .AddScoped<ProjectSocketContext>()

                .AddSingleton<IProject, Project>()
                .AddSingleton<IProjectUser, ProjectUsers>()

                .AddSingleton<ISocketGroup, SocketGroup>()
                .AddSingleton<ISocketRelationship, SocketRelationship>()
                .AddSingleton<ISocketMessage, SocketMessage>()

                .AddSingleton<ISocketUser,SocketUsers>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            BuildServiceProvider
                .ServiceProvider = app.ApplicationServices;

            // 启用Https
            app.UseHttpsRedirection();

            // WS中间件
            app
                .UseWebSocketsMiddleware()
                .UseQueueLoop()
                .UseQueueUntreatedLoop()
                .UseLog4net(loggerFactory);

            // 跨域
            app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());

            app.UseMvc();

        }
    }
}
